package io.sundial.job.bind.impl;

import io.sundial.job.JobContext;
import io.sundial.job.JobParameter;
import io.sundial.job.bind.JobData;
import io.sundial.job.bind.JobField;
import io.sundial.job.bind.JobResolver;
import io.sundial.util.StrKit;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 封装类型 转换器
 *
 * @author Payne 646742615@qq.com
 * 2019/1/7 21:26
 */
public class WrapperResolver implements JobResolver {

    private final Map<String, String> options = new LinkedHashMap<>();

    {
        options.put("null", "null");
        options.put("true", "true");
        options.put("false", "false");
    }

    @Override
    public boolean supports(JobField field) {
        return field.type == Boolean.class
                || field.type == Byte.class
                || field.type == Short.class
                || field.type == Character.class
                || field.type == Integer.class
                || field.type == Float.class
                || field.type == Long.class
                || field.type == Double.class;
    }

    @Override
    public JobParameter resolve(JobField field) {
        String value = field.value != null ? field.value.toString() : null;
        return field.type == Boolean.class
                ? new JobParameter(field.name).setEditor("radio").setOptions(options).setValue(value)
                : new JobParameter(field.name).setEditor("text").setValue(value);
    }

    @Override
    public Object resolve(JobField field, JobData data, JobContext context) {
        String value = data.get(field.name);
        return StrKit.isEmpty(value) ? DEFAULT
                : field.type == Boolean.class ? value.equals("null") ? DEFAULT : Boolean.valueOf(value)
                : field.type == Byte.class ? Byte.valueOf(value)
                : field.type == Short.class ? Short.valueOf(value)
                : field.type == Character.class ? value.charAt(0)
                : field.type == Integer.class ? Integer.valueOf(value)
                : field.type == Float.class ? Float.valueOf(value)
                : field.type == Long.class ? Long.valueOf(value)
                : field.type == Double.class ? Double.valueOf(value)
                : DEFAULT;
    }
}
